package com.amazon.service;

import com.alibaba.fastjson.JSON;
import com.amazon.bo.*;
import com.amazon.dao.*;
import com.amazon.web.util.Send253SMS;
import com.amazon.web.util.SignatureUtil;
import com.amazon.web.util.Tools;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

@Service("productService")
public class ProductService {
    @Resource
    private ProductDao productDao;
    @Resource
    private SMSCodeService smsCodeService;
    @Resource
    private Send253SMS send253SMS;
    @Resource
    I18nService i18nService;
    @Resource
    ShopDao shopDao;
    @Resource
    ShopClassDao shopClassDao;
    @Resource
    ShopGoodsBatchDao shopGoodsBatchDao;
    @Resource
    ShopGoodsDao shopGoodsDao;
    @Resource
    ShopGoodsBatchTraceDao shopGoodsBatchTraceDao;
    @Resource
    EanDao eanDao;





    public Product getProductpBySku(final String SKU) {
        Product m = productDao.getProductpBySku(SKU);
        if (m != null) {
            return m;
        }
        return null;
    }

    //产品列表
    public List<Product> getProductList(int page, int pageSize) {
        List<Product> lst = productDao.getProductList(page, pageSize);
        if (lst != null) {
            return lst;
        }
        return null;
    }

    //获取产品列表
    public List<Product> getProductListForDeal(String conn, final int page, final int pageSize) {
        List<Product> lst = productDao.getProductListForDeal("", page, pageSize);
        List<Product> result = new ArrayList<>();
        if (lst.size() >= 0) {
            for (int i = 0; i < lst.size(); i++) {
                Object o = lst.get(i);
                Object[] f = (Object[]) o;
                Product m = new Product();
                m.setId(Long.parseLong(f[0].toString()));
                m.setTitle(f[1].toString());
                m.setSKU(f[2].toString());
                m.setDescription(f[3].toString());
                m.setItemPackageQuantity(Integer.parseInt(f[4].toString()));
                m.setMSRP(f[5].toString());
                m.setPackageDimensions(f[6].toString());
                result.add(m);
            }
        }
        return result;
    }


    public int getProductsCount(String conn) {
        return productDao.getTotalCount(Product.class, conn);
    }


    public Product addProduct(Product product) {

        if (productDao.getProductBySku(product.getSKU()) == null) {
            product.setId((Long) productDao.add(product));
        } else {

        }
        return product;
    }

    public Product getById(long id) {
        return productDao.getById(id);
    }

    public Product getBySku(String sku) {
        return productDao.getProductBySku(sku);
    }


    public void pullProduct() {


    }

    public boolean productupdate(int goodsid, double amzonprice, String onlineday) {
        return productDao.productupdate(goodsid, amzonprice, onlineday);
    }

    //供应链产品列表
    public List<Product> getProductList(String conn, final int page, final int pageSize) {
        return productDao.getProductList(conn, page, pageSize);
    }

    //更新产品状态
    public boolean productChangeStatus(int productid, int status) {
        return productDao.productChangeStatus(productid, status);
    }

    //更新产品图片
    public boolean productChangeImg(int pid, String img, int status,String newColors) {
        return productDao.productChangeImg(pid, img, status,newColors);
    }

    //更新产品属性
    public boolean productChangeAttr(Product p) {
        return productDao.productChangeAttr(p);
    }

    //更新文描
    public boolean productChangeDesc(int id, int status, String BulletPoint, String Description, String SearchTerms, String Title, String contry) {
        boolean f = productDao.productChangeDesc(id, status, BulletPoint, Description, SearchTerms, Title, contry);
        return true;
    }


    @Scheduled(cron = "0 0/30 * ? * *")
    public Object createBatch() {

        //1 所有店铺
        List<Map<String, Object>> shopList = (List<Map<String, Object>>) shopDao.selectShopAll();


        for (int i = 0; i < shopList.size(); i++) {

            //2 店铺经营分类
            Map<String, Object> shop = shopList.get(i);
            int id = ((BigInteger) shop.get("id")).intValue();

            //3 店铺分类拓展表
            List<ShopClass> classList = shopClassDao.getClassList(id);


            for (int j = 0; j < classList.size(); j++) {


                //4 放入经销列表
                //4.1 生成批次
                ShopGoodsBatch batch = new ShopGoodsBatch();
                batch.setBatchStatus(0);

                //4.2 写入数据库
                Long batchId = (Long) shopGoodsBatchDao.add(batch);
                int shopId = classList.get(j).getShopId();
                int classId = classList.get(j).getProductClassId();

                //4.3 查找商品

                List<Map<String, Object>> productList = shopGoodsDao.getNoPurchaseByShopId(shopId, classId);

                for (Map<String, Object> product : productList) {

                    Long productId = ((BigInteger) product.get("id")).longValue();

                    ShopGoods goods = new ShopGoods();
                    goods.setBatchId(batchId);
                    goods.setProductId(productId);
                    goods.setShopId(shopId);

                    shopGoodsDao.add(goods);
                }
                //4.3 插入经销表
            }
        }
        return null;
    }


    @Scheduled(cron = "0 0/2 * * * ?")
    public Object uploadByBatch() throws Exception {


        ShopGoodsBatch batch = shopGoodsBatchDao.selectFirstShopGoodsBatch();

        if (batch == null)
            return null;

        List<Product> productList = new ArrayList<>();
        Shop shop = null;
        ShopClass shopClass =null;

        List<ShopGoods> goodsList = shopGoodsDao.getGoodsListByBatchId(batch.getId());
        if(goodsList==null){
            batch.setBatchStatus(5);
            shopGoodsBatchDao.update(batch);
            return null;
        }
        for (ShopGoods goods : goodsList) {

            if (shop == null) {
                shop = shopDao.getById(goods.getShopId());
            }
            Product product = productDao.getById(Long.parseLong(String.valueOf(goods.getProductId())));
            productList.add(product);
            if(shopClass==null){
                long shopId=shop.getId();
                long cId=product.getBigClass();
                shopClass=shopClassDao.getShopClassByShopIdAndProductId(shopId, cId);
            }
        }


        Long status = batch.getBatchStatus();
        if (status.intValue() == 0) {

            ShopGoodsBatchTrace result = shopGoodsBatchTraceDao.selectByBatchIdAndUploadStatus(batch.getId(),"0");

            //是否有跟踪记录
            //1 有跟踪记录 ，判断是否上传成功
            if(result!=null) {
                //2 没有跟踪记录，上传商品并创建跟踪记录
                // region 跟踪产品上传记录
                Map<String,Object> sessionResult= Tools.parserJson2Map(SignatureUtil.getFeedSubmissionList(result.getFeedSubmissionId(),shop));

                if(sessionResult==null){
                    return null;
                }

                Map<String,Object> feedSubmissionListResult=(Map<String,Object>)sessionResult.get("GetFeedSubmissionListResult");
                if(feedSubmissionListResult==null){
                    return null;
                }
                Map<String,Object> feedSubmissionInfo=(Map<String,Object>)feedSubmissionListResult.get("FeedSubmissionInfo");
                if(feedSubmissionInfo==null){
                    return null;
                }
                String feedProcessingStatus =feedSubmissionInfo.get("FeedProcessingStatus").toString();



                 if("_DONE_".equals(feedProcessingStatus)){



                    Map<String,Object> processingReport=Tools.parserJson2Map(SignatureUtil.getFeedSubmissionResult(result.getFeedSubmissionId(),shop));
                    if(processingReport==null)
                    {
                        return null;
                    }

                    Map<String,Object> messageMap=(Map<String,Object>)processingReport.get("Message");
                    if(messageMap==null){
                        return null;
                    }
                    Map<String,Object> processingReportMap =(Map<String,Object>)messageMap.get("ProcessingReport");
                    if(processingReportMap==null){
                        return null;
                    }
                    Map<String,Object> processingSummaryMap=(Map<String,Object>) processingReportMap.get("ProcessingSummary");
                    if(processingSummaryMap==null){
                        return null;
                    }
                    String messagesSuccessful = processingSummaryMap.get("MessagesSuccessful").toString();

                    if(Integer.parseInt(messagesSuccessful)>0){
                        result.setUpLoadStatus("0");
                        result.setIfConfirm("Y");

                        shopGoodsBatchTraceDao.update(result);

                        //状态流转到 上传 库存
                        batch.setBatchStatus(1);
                        shopGoodsBatchDao.update(batch);
                    }

                }

                //endregion

            }else{
                //region上传商品
                //shop = shopDao.getById(testId);
                Map<String, Object> result1 = Tools.parserJson2Map(SignatureUtil.uploadProduct(productList, shop,shopClass,eanDao));


                ShopGoodsBatchTrace trace = new ShopGoodsBatchTrace();
                trace.setBatchId(batch.getId());
                trace.setTraceText(JSON.toJSONString(result1));
                trace.setIfConfirm("N");

                Map<String, Object> submitFeedResult = (Map<String, Object>) result1.get("SubmitFeedResult");
                Map<String, Object> feedSubmissionInfo = (Map<String, Object>) submitFeedResult.get("FeedSubmissionInfo");
                feedSubmissionInfo.get("FeedSubmissionId");

                trace.setFeedSubmissionId(String.valueOf(feedSubmissionInfo.get("FeedSubmissionId")));
                trace.setUpLoadStatus("0");

                shopGoodsBatchTraceDao.add(trace);
                //endregion
            }
        } else if (status.intValue() == 1) {


            ShopGoodsBatchTrace result = shopGoodsBatchTraceDao.selectByBatchIdAndUploadStatus(batch.getId(),"1");

            //是否有跟踪记录
            //1 有跟踪记录 ，判断是否上传成功
            if(result!=null) {

                // region 跟踪库存上传记录
                Map<String,Object> sessionResult= Tools.parserJson2Map(SignatureUtil.getFeedSubmissionList(result.getFeedSubmissionId(),shop));

                if(sessionResult==null){
                    return null;
                }

                Map<String,Object> feedSubmissionListResult=(Map<String,Object>)sessionResult.get("GetFeedSubmissionListResult");
                if(feedSubmissionListResult==null){
                    return null;
                }
                Map<String,Object> feedSubmissionInfo=(Map<String,Object>)feedSubmissionListResult.get("FeedSubmissionInfo");
                if(feedSubmissionInfo==null){
                    return null;
                }
                String feedProcessingStatus =feedSubmissionInfo.get("FeedProcessingStatus").toString();



                if("_DONE_".equals(feedProcessingStatus)){



                    Map<String,Object> processingReport=Tools.parserJson2Map(SignatureUtil.getFeedSubmissionResult(result.getFeedSubmissionId(),shop));
                    if(processingReport==null)
                    {
                        return null;
                    }

                    Map<String,Object> messageMap=(Map<String,Object>)processingReport.get("Message");
                    if(messageMap==null){
                        return null;
                    }
                    Map<String,Object> processingReportMap =(Map<String,Object>)messageMap.get("ProcessingReport");
                    if(processingReportMap==null){
                        return null;
                    }
                    Map<String,Object> processingSummaryMap=(Map<String,Object>) processingReportMap.get("ProcessingSummary");
                    if(processingSummaryMap==null){
                        return null;
                    }
                    String messagesSuccessful = processingSummaryMap.get("MessagesSuccessful").toString();

                    if(Integer.parseInt(messagesSuccessful)>0){
                        result.setUpLoadStatus("1");
                        result.setIfConfirm("Y");

                        shopGoodsBatchTraceDao.update(result);

                        //状态流转到 上传 库存
                        batch.setBatchStatus(2);
                        shopGoodsBatchDao.update(batch);
                    }

                }

                //endregion

            }else{
                //region 上传库存
                Map<String, Object> result2 = Tools.parserJson2Map(SignatureUtil.uploadInventory(productList, shop));

                ShopGoodsBatchTrace trace = new ShopGoodsBatchTrace();
                trace.setBatchId(batch.getId());
                trace.setTraceText(JSON.toJSONString(result2));
                trace.setIfConfirm("N");

                Map<String, Object> submitFeedResult = (Map<String, Object>) result2.get("SubmitFeedResult");
                Map<String, Object> feedSubmissionInfo = (Map<String, Object>) submitFeedResult.get("FeedSubmissionInfo");
                feedSubmissionInfo.get("FeedSubmissionId");

                trace.setFeedSubmissionId(String.valueOf(feedSubmissionInfo.get("FeedSubmissionId")));
                trace.setUpLoadStatus("1");

                shopGoodsBatchTraceDao.add(trace);
                // endregion
            }



        } else if (status.intValue() == 2) {


            ShopGoodsBatchTrace result = shopGoodsBatchTraceDao.selectByBatchIdAndUploadStatus(batch.getId(),"2");

            //是否有跟踪记录
            //1 有跟踪记录 ，判断是否上传成功
            if(result!=null) {

                // region 跟踪价格上传记录
                Map<String,Object> sessionResult= Tools.parserJson2Map(SignatureUtil.getFeedSubmissionList(result.getFeedSubmissionId(),shop));

                if(sessionResult==null){
                    return null;
                }

                Map<String,Object> feedSubmissionListResult=(Map<String,Object>)sessionResult.get("GetFeedSubmissionListResult");
                if(feedSubmissionListResult==null){
                    return null;
                }
                Map<String,Object> feedSubmissionInfo=(Map<String,Object>)feedSubmissionListResult.get("FeedSubmissionInfo");
                if(feedSubmissionInfo==null){
                    return null;
                }
                String feedProcessingStatus =feedSubmissionInfo.get("FeedProcessingStatus").toString();



                if("_DONE_".equals(feedProcessingStatus)){



                    Map<String,Object> processingReport=Tools.parserJson2Map(SignatureUtil.getFeedSubmissionResult(result.getFeedSubmissionId(),shop));
                    if(processingReport==null)
                    {
                        return null;
                    }

                    Map<String,Object> messageMap=(Map<String,Object>)processingReport.get("Message");
                    if(messageMap==null){
                        return null;
                    }
                    Map<String,Object> processingReportMap =(Map<String,Object>)messageMap.get("ProcessingReport");
                    if(processingReportMap==null){
                        return null;
                    }
                    Map<String,Object> processingSummaryMap=(Map<String,Object>) processingReportMap.get("ProcessingSummary");
                    if(processingSummaryMap==null){
                        return null;
                    }
                    String messagesSuccessful = processingSummaryMap.get("MessagesSuccessful").toString();

                    if(Integer.parseInt(messagesSuccessful)>0){
                        result.setUpLoadStatus("2");
                        result.setIfConfirm("Y");

                        shopGoodsBatchTraceDao.update(result);

                        //状态流转到 上传 库存
                        batch.setBatchStatus(3);
                        shopGoodsBatchDao.update(batch);
                    }

                }

                //endregion

            }else{

                // region 上传价格
                Map<String, Object> result3 = Tools.parserJson2Map(SignatureUtil.uploadPrice(productList, shop));

                ShopGoodsBatchTrace trace = new ShopGoodsBatchTrace();
                trace.setBatchId(batch.getId());
                trace.setTraceText(JSON.toJSONString(result3));
                trace.setIfConfirm("N");

                Map<String, Object> submitFeedResult = (Map<String, Object>) result3.get("SubmitFeedResult");
                Map<String, Object> feedSubmissionInfo = (Map<String, Object>) submitFeedResult.get("FeedSubmissionInfo");
                feedSubmissionInfo.get("FeedSubmissionId");

                trace.setFeedSubmissionId(String.valueOf(feedSubmissionInfo.get("FeedSubmissionId")));
                trace.setUpLoadStatus("2");

                shopGoodsBatchTraceDao.add(trace);
                // endregion
            }



        } else if (status.intValue() == 3) {


            ShopGoodsBatchTrace result = shopGoodsBatchTraceDao.selectByBatchIdAndUploadStatus(batch.getId(),"3");

            //是否有跟踪记录
            //1 有跟踪记录 ，判断是否上传成功
            if(result!=null) {

                // region 跟踪图片上传记录
                Map<String,Object> sessionResult= Tools.parserJson2Map(SignatureUtil.getFeedSubmissionList(result.getFeedSubmissionId(),shop));

                if(sessionResult==null){
                    return null;
                }

                Map<String,Object> feedSubmissionListResult=(Map<String,Object>)sessionResult.get("GetFeedSubmissionListResult");
                if(feedSubmissionListResult==null){
                    return null;
                }
                Map<String,Object> feedSubmissionInfo=(Map<String,Object>)feedSubmissionListResult.get("FeedSubmissionInfo");
                if(feedSubmissionInfo==null){
                    return null;
                }
                String feedProcessingStatus =feedSubmissionInfo.get("FeedProcessingStatus").toString();



                if("_DONE_".equals(feedProcessingStatus)){



                    Map<String,Object> processingReport=Tools.parserJson2Map(SignatureUtil.getFeedSubmissionResult(result.getFeedSubmissionId(),shop));
                    if(processingReport==null)
                    {
                        return null;
                    }

                    Map<String,Object> messageMap=(Map<String,Object>)processingReport.get("Message");
                    if(messageMap==null){
                        return null;
                    }
                    Map<String,Object> processingReportMap =(Map<String,Object>)messageMap.get("ProcessingReport");
                    if(processingReportMap==null){
                        return null;
                    }
                    Map<String,Object> processingSummaryMap=(Map<String,Object>) processingReportMap.get("ProcessingSummary");
                    if(processingSummaryMap==null){
                        return null;
                    }
                    String messagesSuccessful = processingSummaryMap.get("MessagesSuccessful").toString();

                    if(Integer.parseInt(messagesSuccessful)>0){
                        result.setUpLoadStatus("3");
                        result.setIfConfirm("Y");

                        shopGoodsBatchTraceDao.update(result);

                        //状态流转到 上传 库存
                        batch.setBatchStatus(4);
                        shopGoodsBatchDao.update(batch);
                    }

                }

                //endregion

            }else{

                //region 上传图片
                Map<String, Object> result4 = Tools.parserJson2Map(SignatureUtil.uploadImage(productList, shop));

                ShopGoodsBatchTrace trace = new ShopGoodsBatchTrace();
                trace.setBatchId(batch.getId());
                trace.setTraceText(JSON.toJSONString(result4));
                trace.setIfConfirm("N");

                Map<String, Object> submitFeedResult = (Map<String, Object>) result4.get("SubmitFeedResult");
                Map<String, Object> feedSubmissionInfo = (Map<String, Object>) submitFeedResult.get("FeedSubmissionInfo");
                feedSubmissionInfo.get("FeedSubmissionId");

                trace.setFeedSubmissionId(String.valueOf(feedSubmissionInfo.get("FeedSubmissionId")));
                trace.setUpLoadStatus("3");

                shopGoodsBatchTraceDao.add(trace);
                //endregion
            }



        } else if (status.intValue() == 4) {



                ShopGoodsBatchTrace result = shopGoodsBatchTraceDao.selectByBatchIdAndUploadStatus(batch.getId(),"4");

                //是否有跟踪记录
                //1 有跟踪记录 ，判断是否上传成功
                if(result!=null) {

                    // region 跟踪变体上传记录
                    Map<String,Object> sessionResult= Tools.parserJson2Map(SignatureUtil.getFeedSubmissionList(result.getFeedSubmissionId(),shop));

                    if(sessionResult==null){
                        return null;
                    }

                    Map<String,Object> feedSubmissionListResult=(Map<String,Object>)sessionResult.get("GetFeedSubmissionListResult");
                    if(feedSubmissionListResult==null){
                        return null;
                    }
                    Map<String,Object> feedSubmissionInfo=(Map<String,Object>)feedSubmissionListResult.get("FeedSubmissionInfo");
                    if(feedSubmissionInfo==null){
                        return null;
                    }
                    String feedProcessingStatus =feedSubmissionInfo.get("FeedProcessingStatus").toString();



                    if("_DONE_".equals(feedProcessingStatus)){



                        Map<String,Object> processingReport=Tools.parserJson2Map(SignatureUtil.getFeedSubmissionResult(result.getFeedSubmissionId(),shop));
                        if(processingReport==null)
                        {
                            return null;
                        }

                        Map<String,Object> messageMap=(Map<String,Object>)processingReport.get("Message");
                        if(messageMap==null){
                            return null;
                        }
                        Map<String,Object> processingReportMap =(Map<String,Object>)messageMap.get("ProcessingReport");
                        if(processingReportMap==null){
                            return null;
                        }
                        Map<String,Object> processingSummaryMap=(Map<String,Object>) processingReportMap.get("ProcessingSummary");
                        if(processingSummaryMap==null){
                            return null;
                        }
                        String messagesSuccessful = processingSummaryMap.get("MessagesSuccessful").toString();

                        if(Integer.parseInt(messagesSuccessful)>0){
                            result.setUpLoadStatus("4");
                            result.setIfConfirm("Y");

                            shopGoodsBatchTraceDao.update(result);

                            //状态流转到 上传 库存
                            batch.setBatchStatus(5);
                            shopGoodsBatchDao.update(batch);
                        }

                    }

                    //endregion

                }else{


                //region 上传变体
                Map<String, Object> result5 = Tools.parserJson2Map(SignatureUtil.uploadVariation(productList, shop));

                ShopGoodsBatchTrace trace = new ShopGoodsBatchTrace();
                trace.setBatchId(batch.getId());
                trace.setTraceText(JSON.toJSONString(result5));
                trace.setIfConfirm("N");

                Map<String, Object> submitFeedResult = (Map<String, Object>) result5.get("SubmitFeedResult");
                Map<String, Object> feedSubmissionInfo = (Map<String, Object>) submitFeedResult.get("FeedSubmissionInfo");
                feedSubmissionInfo.get("FeedSubmissionId");

                trace.setFeedSubmissionId(String.valueOf(feedSubmissionInfo.get("FeedSubmissionId")));
                trace.setUpLoadStatus("4");

                shopGoodsBatchTraceDao.add(trace);
                //endregion
            }
        }
        return null;
    }
    //更新说明-替换
    public boolean updateChDesc(String item,String oriv,String repv){
        try {
            return productDao.updateChDesc(item,oriv,repv);
        }catch (Exception ex){
            return false;
        }
    }

    //刊登撒谎那个品列表
    public Object getPublishList(int shopid,String  sku,String title,final int page, final int pageSize){
        return productDao.getPublishList(shopid,sku,title,page,pageSize);
    }
    //刊登商品数
    public int getPublicCount(int shopid,String  sku,String title){
        return productDao.getPublicCount(shopid,sku,title);
    }
}
